import {
  upload,
  checkUpload,
  uploadOSS,
  globalData
} from '../../utils/request'
import {
  getCardDetails,
  customerService,
  getOSSAutograph
} from '../../apis/card';
const app = getApp();

Page({
  data: {
    imageList: ['', '', '', '', '', ''],
    uploadList: [],
    wechatList: [],
    OSSAutograph: {}
  },

  onLoad(options) {
    this.setData({
      ...options
    });
    this.getOSSAutograph();
    if (options.type === 'edit') this.getImages(options.cardId);
    this.getCustomerService();
  },

  // 获取相册
  getImages(id) {
    getCardDetails(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        if (data.imageList) {
          data.imageList.forEach((v, i) => {
            if (!new RegExp('^https://').test(v) && !new RegExp('^http://').test(v)) {
              this.data.imageList[i] = app.globalData.url + v;
            } else {
              this.data.imageList[i] = v;
            };
            this.data.uploadList[i] = v;
          });
        };
        if (data.musicId) {
          this.setData({
            musicId: data.musicId,
            musicIndex: data.musicId - 1
          });
        };
        this.setData({
          imageList: this.data.imageList,
          uploadList: this.data.uploadList,
          cardInfo: data
        });
      };
    });
  },
  // 客服
  getCustomerService() {
    customerService().then(res => {
      let {
        rows
      } = res.data;
      this.setData({
        wechatList: rows
      });
    });
  },

  deleteImage(e) {
    let {
      index
    } = e.currentTarget.dataset;
    this.data.imageList[index] = '';
    if (this.data.uploadList[index]) this.data.uploadList.splice(index, 1);
    this.setData({
      imageList: this.data.imageList,
      uploadList: this.data.uploadList
    });
  },

  selectImage(e) {
    let {
      index
    } = e.currentTarget.dataset, num = 0;
    this.data.imageList.forEach(v => {
      if (v === '') {
        num++;
      };
    });
    wx.chooseImage({
      count: num,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        console.log(res);
        let {
          tempFilePaths
        } = res, arr = this.data.imageList, index = [];
        arr.forEach((v, i) => {
          if (v === '') index.push(i)
        });
        tempFilePaths.forEach((v, i) => {
          arr[index[i]] = v;
        });
        this.setData({
          imageList: arr
        });
      }
    });
  },

  // 上传
  uploadImage(list, index) {
    wx.showLoading({
      title: '上传中...',
      mask: true
    });
    if (index == list.length) {
      let str = this.data.uploadList.join(',');
      wx.hideLoading({
        success: res => {
          wx.showToast({
            title: '上传完成',
            icon: 'success',
            duration: 1000,
            mask: true,
            success: res => {
              let timer = setTimeout(() => {
                wx.navigateTo({
                  url: `/pages/editCard/index?images=${str}`
                });
                clearTimeout(timer);
              }, 1000);
            }
          })
        }
      });
    } else {
      upload(this.data.imageList[list[index]]).then(res => {
        let {
          code,
          data
        } = JSON.parse(res.data);
        if (code === 200) {
          this.setData({
            [`uploadList[${list[index]}]`]: data,
            [`imageList[${list[index]}]`]: !new RegExp('https://').test(data) && !new RegExp('http://').test(data) ? app.globalData.url + data : data
          });
          index++;
          this.uploadImage(list, index);
        };
      });
    };
  },
  editUpload(arr, index) {
    wx.showLoading({
      title: '上传中...',
    });
    if (index === arr.length) {
      let arr = new Array;
      this.data.imageList.forEach(v => {
        if (v !== '') {
          arr.push(v);
        };
      });
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2];
      prevPage.data.form.images = this.data.uploadList.join(',');
      prevPage.data.form.imageList = this.data.uploadList;
      prevPage.setData({
        form: prevPage.data.form
      });
      wx.navigateBack({
        delta: 1
      });
    } else {
      upload(this.data.imageList[arr[index]]).then(res => {
        let {
          code,
          data
        } = JSON.parse(res.data);
        if (code === 200) {
          this.data.uploadList[arr[index]] = data;
          this.setData({
            uploadList: this.data.uploadList
          });
          index++;
          this.editUpload(arr, index);
        };
      });
    };
  },

  // OSS签名
  getOSSAutograph() {
    getOSSAutograph().then(res => {
      if (res.data.code === 200) {
        this.setData({
          OSSAutograph: res.data.data
        });
      };
    });
  },

  // 校验
  imagesCheck(arr, i) {
    wx.showLoading({
      title: '校验中...'
    });
    if (i === arr.length) {
      this.imageUploadOSS(arr, 0);
    } else {
      checkUpload(this.data.imageList[arr[i]]).then(res => {
        let {
          code
        } = JSON.parse(res.data);
        if (code === 200) {
          i++;
          this.imagesCheck(arr, i);
        } else {
          wx.hideLoading({});
          wx.showToast({
            title: `第${arr[i]+1}张图片违规，请重新上传`,
            icon: 'none',
            duration: 2000
          });
        };
      });
    };
  },
  // 上传OSS
  imageUploadOSS(arr, i) {
    wx.showLoading({
      title: '上传中...'
    });
    if (i === arr.length) {
      wx.hideLoading({});
      wx.showToast({
        title: '上传成功',
        icon: 'success',
        mask: true,
        duration: 1000,
        success: res => {
          let timer = setTimeout(() => {
            if (this.data.type === 'edit') {
              let pages = getCurrentPages();
              let prevPage = pages[pages.length - 2];
              prevPage.setData({
                ['form.images']: this.data.uploadList.join(','),
                ['form.imageList']: this.data.uploadList
              });
              wx.navigateBack({
                delta: 1
              });
            } else {
              wx.navigateTo({
                url: `/pages/editCard/index?images=${this.data.uploadList.join(',')}`
              });
            };
            clearTimeout(timer);
          }, 1000);
        }
      });
    } else {
      let fileName = globalData.userId + '-' + new Date().getTime() + '.png';
      uploadOSS(this.data.imageList[arr[i]], this.data.OSSAutograph.host, {
        key: `${this.data.OSSAutograph.dir}/${fileName}`,
        policy: this.data.OSSAutograph.policy,
        OSSAccessKeyId: this.data.OSSAutograph.accessid,
        signature: this.data.OSSAutograph.signature,
        success_action_status: '200'
      }).then(res => {
        if (res.statusCode === 200) {
          this.setData({
            [`uploadList[${arr[i]}]`]: `${this.data.OSSAutograph.host}/${this.data.OSSAutograph.dir}/${fileName}`,
            [`imageList[${arr[i]}]`]: `${this.data.OSSAutograph.host}/${this.data.OSSAutograph.dir}/${fileName}`
          });
          i++;
          this.imageUploadOSS(arr, i);
        };
      });
    };
  },

  // 确认
  confirm() {
    let num = 0;
    this.data.imageList.forEach(v => {
      if (v !== '') {
        num++;
      };
    });
    if (num < 2) {
      wx.showToast({
        title: '请至少上传两张图片',
        icon: 'none',
        duration: 1500,
        mask: true
      });
      return
    };
    let arr = new Array;
    if (this.data.type === 'edit') {
      this.data.imageList.forEach((v, i) => {
        if (new RegExp('^wxfile://').test(v) || new RegExp('^http://tmp').test(v)) {
          arr.push(i);
        };
      });
      this.imagesCheck(arr, 0);
    } else {
      this.data.imageList.forEach((v, i) => {
        if (v !== '' && (new RegExp('^wxfile://').test(v) || new RegExp('^http://tmp').test(v))) {
          arr.push(i);
        };
      });
      this.imagesCheck(arr, 0);
    };
  }
})